# coding=utf-8
import os
import sys
from xml.dom.minidom import parse
import xml.etree.ElementTree as ET
import xml.dom.minidom
import xlwt
import xlrd
import datetime


#解析函数，解析特有的界面翻译
def parseQml(qmlName):

    dom = parse('ko.xml')
    # 获取文档元素对象
    data = dom.documentElement
    
    #获取content#
    contentc = data.getElementsByTagName('context')
    

    #构建字典
    returnData = {}

    for content in contentc:
        #获取文件名字
        qml = content.getElementsByTagName('name')[0].childNodes[0].nodeValue
        print("输出", qml)
        if qmlName != '':
            if qml == qmlName:
                #目的qml 翻译文件
                #解析每个的message
                messages = content.getElementsByTagName('message')
                transData = {}
                for message in messages:
                   #对每个message  进行判断是否无效
                    translation = message.getElementsByTagName('translation')
                    if (translation[0].hasAttribute('type') and translation[0].getAttribute('type') != "unfinished"):
                        print("无效字符")
                        continue
                    else:
                        print("有效字符")
                        source = message.getElementsByTagName('source')[0].childNodes[0].nodeValue
                        translatess = ""  #默认是空值，有值再放入
                        if translation[0].childNodes.length > 0:
                            translatess = translation[0].childNodes[0].nodeValue
                            print('qmlname', qml, 'source', source, 'translate',translatess)
                            transData[source] = translatess
                            continue 
                returnData[qml] = transData

                return returnData
        else: 
            #对每个qml进行导出操作
            messages = content.getElementsByTagName('message')
            transData = {}
            for message in messages:
                #对每个message  进行判断是否无效
                translation = message.getElementsByTagName('translation')
                if (translation[0].hasAttribute('type') and translation[0].getAttribute('type') != "unfinished"):
                    print("无效字符")
                     
                    continue
                else:
                    print("有效字符")
                     
                    x = message.getElementsByTagName('source')[0]
                    if(x.childNodes.length >0):
                        y = x.childNodes[0]
                        source= y.nodeValue
                    else:
                         print('qmlname', qml, 'cerror',  message.getElementsByTagName('location')[0].getAttribute('line'))
                          
                    
                    translatess = ""  #默认是空值，有值再放入
                    if translation[0].childNodes.length > 0:
                        translatess = translation[0].childNodes[0].nodeValue
                        print('qmlname', qml, 'source', source, 'translate',translatess)
                         
                        
                    transData[source] = translatess
                    continue 
            returnData[qml] = transData          
    return returnData



def printAll(resultData):
    #打印嵌套字典的数据
    #打印第一个key
    print('打印')
    for firstKey, data in resultData.items():
        print('第一个key', firstKey)
        #打印第二层
        for key, value in data.items():
            print('打印第二层', key, '数值', value)
    return


def outExcel(input, outname):
    #创建xls的操作对象
    wb = xlwt.Workbook()
    #新增表单
    sh1 = wb.add_sheet('翻译')
    #处理抬头
    #定义行数
    xlind = 1
    sh1.write(0, 0, '文件名称')
    sh1.write(0, 1, '源文')
    sh1.write(0, 2, '中文')
    #开始写入数据
    for firstKey, data in input.items():
        #print('第一个key' , firstKey)
        #打印第二层
        for key, value in data.items():
            print('打印第二层', key, '数值', value)
            #写入数据
            sh1.write(xlind, 0, firstKey)
            sh1.write(xlind, 1, key)
            sh1.write(xlind, 2, value)
            xlind += 1
    #保存文件
    wb.save(outname)

    return


def importExcelToXML():

    result = importExcel('ko1.xls')
    printAll(result)
    writeToXML(result)
    return


def importExcel(name):
    #导入excel
    importE = xlrd.open_workbook(name,encoding_override = 'utf-8')
    #读取第一张表单
    sheetr1 = importE.sheets()[0]
    #获取行数
    sheetr1_nrows = sheetr1.nrows
    importData = {}
    for r in range(1, sheetr1_nrows):
        #获取每行数据，包装成嵌套字典
        key1 = sheetr1.cell_value(r, 0)  #第一列数据
        print('第一个数据', key1)
        key2 = sheetr1.cell_value(r, 1)
        value1 = sheetr1.cell_value(r, 2)
        #封装数据
        insertData(importData, key1, key2, value1)

    return importData


def writeToXML(excelData):
    #先读取xml文件
    tree = ET.parse('ko.xml')
    root = tree.getroot()
    for element in root.findall('context'):
        #访问ts里面的信息
        #获取到qmlname
        qmlname = element.find('name').text
        #遍历每个message字段
        for secondmess in element.findall('message'):
            #提取source字段来查找翻译
            updateSource = secondmess.find('source').text
            if findkeyFromDirt(excelData, qmlname, updateSource):
                #如果查找到这个数据，更新数据
                secondmess.find(
                    'translation').text = excelData[qmlname][updateSource]
                print('更新内容', secondmess.find('translation').text)
                #判断是否出现未完成，有则删掉这个属性
                print('更新属性',
                      ('type' in secondmess.find('translation').attrib))
                if ('type' in secondmess.find('translation').attrib
                    ) and secondmess.find(
                        'translation').attrib['type'] == 'unfinished':
                    #去除属性
                    secondmess.find('translation').attrib.pop('type')

    tree.write('ko1.xml')

    return


def findkeyFromDirt(dirt, firstkey, secondkey):
    if firstkey in dirt:
        if secondkey in dirt[firstkey]:
            return True

    return False


def insertData(dirt, key1, key2, key3):
    if key1 in dirt:
        dirt[key1][key2] = key3
    else:
        ddirt = {key2: key3}
        dirt[key1] = ddirt
    return dirt


def importXMLToExcel():
    resultData = parseQml('DisplayText')
    outExcel(resultData, "ko.xls")
    return


def mergeExcel():
    #导入excel  第一个 第二个
    data1 = importExcel('zh.xls')
    data2 = importExcel('ko.xls')
    #定义输入正常的字典  和异常字典
    outputDir = {}
    errorDir = {}
    for key1, data in data1.items():
        #遍历中文
        for key2, value in data.items():
            if findkeyFromDirt(data2, key1, key2):
                kr = [value, data2[key1][key2]]
                insertData(outputDir, key1, key2, kr)
            else:
                insertData(errorDir, key1, key2, value)
    if len(errorDir) > 0:
        outExcel(errorDir, 'error.xls')  #保存错误的中文索引

    #保存中韩文对照
    #创建xls的操作对象
    wb = xlwt.Workbook()
    #新增表单
    sh1 = wb.add_sheet('翻译')
    #处理抬头
    #定义行数
    xlind = 1
    sh1.write(0, 0, '文件名称')
    sh1.write(0, 1, '源文')
    sh1.write(0, 2, '中文')
    sh1.write(0, 3, 'korean')
    #开始写入数据
    for firstKey, data in outputDir.items():
        #print('第一个key' , firstKey)
        #打印第二层
        for key, value in data.items():
            print('打印第二层', key, '数值', value)
            #写入数据
            sh1.write(xlind, 0, firstKey)
            sh1.write(xlind, 1, key)
            sh1.write(xlind, 2, value[0])
            sh1.write(xlind, 3, value[1])
            xlind += 1
    #保存文件
    wb.save('zh-ko.xls')

    return


def spliteExcel(xls):
    #导入excel
    importE = xlrd.open_workbook(xls)
    #读取第一张表单
    sheetr1 = importE.sheets()[0]
    #获取行数
    sheetr1_nrows = sheetr1.nrows
    #获取列数
    sheetr1_ncols = sheetr1.ncols
    wb = xlwt.Workbook()
    #新增表单
    
    #通过列来获取数据
    c1 = sheetr1.col_values(0)
    c2 = sheetr1.col_values(1)
    for c in range(2,sheetr1_ncols) :
        print(sheetr1.cell_value(0 ,c))
        sh1 = wb.add_sheet(sheetr1.cell_value(0 ,c))
        cData = sheetr1.col_values(c)
        for row in range(sheetr1_nrows):
            sh1.write(row, 0, c1[row])
            sh1.write(row, 1, c2[row])
            sh1.write(row, 2, cData[row])
    wb.save('splite.xls')
    





if __name__ == "__main__":
    #解析xml
    #importXMLToExcel()

    #合并excel
    #mergeExcel()

    #拆分excel
    #spliteExcel('zh-ko.xls')

    #解析excel
    importExcelToXML()
